package com.markyao.service.impl;

import com.alibaba.fastjson.JSON;
import com.markyao.dao.mapper.UserMapper;
import com.markyao.dao.pojo.User;
import com.markyao.service.UserService;
import com.markyao.utils.JWTUtils;
import com.markyao.vo.Result;
import com.markyao.vo.ResultCode;
import com.markyao.vo.parmas.UserParmas;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    private static final String md5mm = "123456Mky!@#$$";
    @Autowired
    UserMapper userMapper;
//    @Autowired
//    RedisTemplate<String,String>redisTemplate;
    @Override
    public Result addUser(UserParmas userParmas) {
        /*
        注册
        1检查参数是否违法
        2从数据库查找用户名是否重复
        3生成加密密码插入数据库
        4生成token放入redis
         */
        //1
        String username = userParmas.getUsername();
        String password = userParmas.getPassword();
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            return new Result(false,ResultCode.PARMAS_IS_BLANK.getMsg(),ResultCode.PARMAS_IS_BLANK.getCode(),null);
        }
        //2
        User u=new User();
        u.setUsername(username);
        User uu = userMapper.findByUsername(u);
        if(uu!=null){
            return new Result(false, ResultCode.REGISTER_USERNAME_EXIST_ERROR.getMsg(),  ResultCode.REGISTER_USERNAME_EXIST_ERROR.getCode(), null);
        }
        //3
        u.setPassword(DigestUtils.md5Hex(password+md5mm));
        u.setModifiedUser(username);
        u.setCreatedTime(new Date());
        userMapper.addUser(u);
        //4
//        String token = JWTUtils.createToken(u.getUid());
//        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(u),1, TimeUnit.DAYS);
        return new Result(true,ResultCode.REGISTER_SUCCESS.getMsg(), ResultCode.REGISTER_SUCCESS.getCode(), null);
    }

    @Override
    public Result findByUser(UserParmas userParmas) {

        /*
        登录
        1.检查参数是否合法
        2.加密密码查询数据库
        3.生成token插入redis
        4.把token返回前端
         */
        //1
        String username = userParmas.getUsername();
        String password = userParmas.getPassword();
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            return new Result(false,ResultCode.PARMAS_IS_BLANK.getMsg() ,ResultCode.PARMAS_IS_BLANK.getCode(),null);
        }
        //2
        User u=new User();
        u.setUsername(username);
        u.setPassword(DigestUtils.md5Hex(password+md5mm));
        User user=userMapper.findByNameAndPwd(u);
        if(user==null){
            return new Result(false,ResultCode.LOGIN_ERROR.getMsg(), ResultCode.LOGIN_ERROR.getCode(),null);
        }
//        3.
//        String token = JWTUtils.createToken(user.getUid());
//        redisTemplate.opsForValue().set("TOKEN_"+token,JSON.toJSONString(user),1, TimeUnit.DAYS);
//        4
        return new Result(true,ResultCode.LOGIN_SUCCESS.getMsg(), ResultCode.LOGIN_SUCCESS.getCode(), user);
    }

    @Override
    public Result changePwd(UserParmas userParmas) {
        //确认旧密码是否正确
        String oldPassword = userParmas.getOldPassword();
        String s = DigestUtils.md5Hex(oldPassword+md5mm);
        String username = userParmas.getUsername();
        User user=userMapper.checkOldPwd(username,s);
        if(user==null){
            return new Result(false,ResultCode.UPDATE_PWD_ERROR.getMsg() ,ResultCode.UPDATE_PWD_ERROR.getCode(),null);
        }
        //密码正确之后开始修改密码
        String newPassword = userParmas.getNewPassword();
        user.setPassword(DigestUtils.md5Hex(newPassword+md5mm));
        userMapper.update(user);
        return new Result(true,ResultCode.UPDATE_PWD_SUCCESS.getMsg(), ResultCode.UPDATE_PWD_SUCCESS.getCode(), null);
    }

    @Override
    public Result findByUid(Integer uid) {
        User user=userMapper.findByUid(uid);
        return new Result(true,"findOK",1001,user);
    }

    @Override
    public Result updateInfo(UserParmas userParmas) {
        userParmas.setModifiedTime(new Date());
        userMapper.updateInfo(userParmas);
        return new Result(true,"修改成功",1001,null);
    }

    @Override
    public Result updateAvater(User user) {
        user.setModifiedUser(user.getUsername());
        user.setModifiedTime(new Date());
        userMapper.updateAvaterByUid(user);
        return new Result(true,"头像修改成功",1002,user.getAvatar());
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result login(UserParmas loginParmas) {
         /*
        1.检查参数是否合法
        2.根据用户名和密码查找数据库是否存在
        3.如果不存在登陆失败
        4.如果存在使用jwt 生成token返回前端
        5.token放入redis token:user信息 设置过期时间，登录认证的时候先认证token字符串是否合法，去redis认证是否存在。
         */
        String account = loginParmas.getUsername();
        String password = loginParmas.getPassword();
        if(StringUtils.isBlank(account)||StringUtils.isBlank(password)){
            return Result.fail(-999,"信息填写有误");
        }
        password= DigestUtils.md5Hex(password+md5mm);//md5加密密码
        User user = new User();
        user.setUsername(account);
        user.setPassword(password);
        User sysUser= userMapper.findByUsername(user);
        if(sysUser==null){
            return Result.fail(-888, "用户不存在或密码填写错误!");
        }
        String token = JWTUtils.createToken(sysUser.getUid());
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        return Result.success(token);
    }
    @Override
    public User checkT(String token) {
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if(map==null){
            return null;
        }
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String  userJson = operations.get("TOKEN_" + token);
        if(StringUtils.isBlank(userJson)){
            return null;
        }
        User sysUser = JSON.parseObject(userJson, User.class);
        return sysUser;
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.success(null);
    }
//    @Override
//    public Result findUserBytoken(String token) {
//        /*
//        通过token查找
//        1校验是否合法
//        2通过redis查找token
//        3返回
//         */
//        if (StringUtils.isBlank(token)){
//            return new Result(false,ResultCode.TOKEN_NOT_EXIST.getMsg(),ResultCode.TOKEN_NOT_EXIST.getCode(),null);
//        }
//        User user = checkT(token);
//        if (user==null){
//            return new Result(false,ResultCode.TOKEN_ERROR.getMsg(),ResultCode.TOKEN_ERROR.getCode(),null);
//        }
//        return new Result(true,ResultCode.LOGIN_SUCCESS.getMsg(), ResultCode.LOGIN_SUCCESS.getCode(), user);
//    }

//    @Override
//    public User checkT(String token) {
//        //检查
//        if(StringUtils.isBlank(token)){
//            return null;
//        }
//        Map<String, Object> map = JWTUtils.checkToken(token);
//        if(map==null){
//            return null;
//        }
//        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
//        if(StringUtils.isBlank(userJson)){
//            return null;
//        }
//        User sysUser = JSON.parseObject(userJson, User.class);
//        return sysUser;
//    }

}
